//
//  GamesViewController.m
//  KG
//
//  Created by Eugene Braginets on 26.04.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GamesViewController.h"
#import "GameCell.h"
#import "bannerView.h"
#import "Competition.h"
#import "Game.h"
#import "AppDelegate.h"

@implementation GamesViewController
@synthesize errorMessage = _errorMessage;
@synthesize tableView=_tableView;
@synthesize pickerView = _pickerView;
@synthesize segmentedControl = _segmentedControl;
@synthesize myCell1=_myCell1;
@synthesize bannerViewController=_bannerViewController;
@synthesize compLevel = _compLevel;
@synthesize Competitions = _Competitions;
@synthesize games=_games;
@synthesize competitionsList=_competitionsList;
@synthesize activityIndicator = _activityIndicator;
@synthesize boardItem=_boardItem;
@synthesize reqURL=_reqURL;
@synthesize reqPanelURL=_reqPanelURL;
@synthesize reqPanels=_reqPanels;

#pragma mark - methods
- (id) initWithItem:(NSString*) item {
    self = [super initWithNibName:@"GamesViewController" bundle:nil];
    if (self) {

        
        
        NSLog(@"Init with item %@!",item);
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector: @selector(refresh:)
                                                     name:kGameItem object: nil];	
        self.boardItem=item;
        [self.tableView setHidden:YES];
        self.games=[[myAppDelegate dataArraysStore] objectForKey:item];
        
    }
    return self;
}

- (void) updateUI:(NSString*)ok {

    self.games=[[myAppDelegate dataArraysStore] objectForKey:self.boardItem];
//    NSLog(self.games);
   [self.activityIndicator setHidden:YES];
    [self.errorMessage setHidden:YES];

    
    NSLog(@"updateUI with: %@",ok);
    if ([ok isEqual:@"err"]) {
        NSLog(@"error");
            [self.errorMessage setHidden:NO];
            return;
    }
    
    NSLog(@"UpdateUI with good data!");
    
//   
//          
//    self.myCell1=nil;
    [self.tableView reloadData];
    NSLog(@"reloadData!");
    
    [self.pickerView reloadAllComponents];
    [self.tableView setHidden:NO];
    [self.compLevel setEnabled:YES];
    [self.Competitions setEnabled:YES];
    
}
- (void) refresh:(NSNotification*) object {
    
        NSString* type=[[object object] objectAtIndex:0];
        NSString* state=[[object object] objectAtIndex:1];
        
        NSLog(@"REFRESHING BoardItem: %@",self.boardItem);
        NSLog(@"Object: %@",type);
        NSLog(@"State: %@",state);

        if (![type isEqual:self.boardItem]) {
            return;
        }

       [self performSelectorOnMainThread:@selector(updateUI:) withObject:state waitUntilDone:NO];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//        NSDictionary* _games=[[NSDictionary alloc] init ];
        
    }
    return self;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
//    NSLog(@"Games: %@",self.games);
    
    [self.errorMessage setHidden:NO];
    self.reqURL=[self.reqPanels objectAtIndex:0];
    
        
    if (self.games) {
        [self.activityIndicator setHidden:YES];
        [self.errorMessage setHidden:YES];
    }
    int i;
    for (i=0;i<4;i++) {
    [self.segmentedControl setTitle:[kCompPanel objectAtIndex:i] forSegmentAtIndex:i];
    }
    
    
    if (([self.title isEqualToString:kFootFixtures]) ||
        ([self.title isEqualToString:kHurlFixtures]) ) {
        [self.segmentedControl setTitle:[NSString stringWithFormat:@"Next %@",[kCompPanel objectAtIndex:0] ] forSegmentAtIndex:0];
    }
    else {
        [self.segmentedControl setTitle:[NSString stringWithFormat:@"Last %@",[kCompPanel objectAtIndex:0] ] forSegmentAtIndex:0];
    }
        
    bannerView *bannerVC=[[bannerView alloc] init];
    [self.view addSubview:bannerVC.view];
    [bannerVC animate];
    self.bannerViewController=bannerVC;  
    
//    CGRect frame=CGRectMake(0, 150, 320, 700);
//    [self.Competitions.titleLabel setFrame:frame];
//    [self.pickerView setFrame:frame];
    
    [self refresh:nil];
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [[NSNotificationCenter defaultCenter] removeObserver:kGameItem];
    
    [self setTableView:nil];
    [self setPickerView:nil];
    [self setSegmentedControl:nil];
    [self setCompLevel:nil];
    [self setCompetitions:nil];
    [self setActivityIndicator:nil];
    [self setErrorMessage:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark - Custom methods
// segment action
- (IBAction)segmentedControlSwitched:(id)sender {
NSLog (@"Selected: %d",self.segmentedControl.selectedSegmentIndex);
    [self.errorMessage setHidden:NO];
    [self.Competitions setEnabled:NO];
//    [self.compLevel setEnabled:NO];
    [self.tableView setHidden:YES];
    [self.activityIndicator setHidden:NO];
  
            //get Football fixtures, next 7 days, Senior, All competitions
            self.boardItem=[NSString stringWithFormat:@"%@%@%@%@",kGameItem,self.title,[kCompPanel objectAtIndex:self.segmentedControl.selectedSegmentIndex],self.compLevel.titleLabel.text];
            self.reqURL=[self.reqPanels objectAtIndex:self.segmentedControl.selectedSegmentIndex];
     
    
//    [self.compLevel setTitle:@"Senior" forState:UIControlStateNormal];
//    [self.compLevel setTitle:@"Senior" forState:UIControlStateDisabled];
//    [self.compLevel setTag:0];

    [self.Competitions setTag:0];
    
    self.boardItem=[NSString stringWithFormat:@"%@%@%@%@",kGameItem,self.title,[kCompPanel objectAtIndex:self.segmentedControl.selectedSegmentIndex],self.compLevel.titleLabel.text];

    
    
        [myAppDelegate getData:[NSString stringWithFormat:@"%@compLevel=%@",self.reqURL,self.compLevel.titleLabel.text]
                       andType:self.boardItem];   
        
}

- (IBAction)selectCompetition:(id)sender {
    [self.pickerView setTag:2];
    [self.pickerView setAlpha:0];
    [self.pickerView selectRow:self.Competitions.tag inComponent:0 animated:NO];
    [self.pickerView setHidden:NO];
    [self.compLevel setEnabled:NO];
    [self.Competitions setEnabled:NO];
    [self.segmentedControl setEnabled:NO];
    [self.pickerView reloadComponent:0];
    [UIView animateWithDuration:0.5 animations:^{
        self.pickerView.alpha=1;
    }];   
    
}

- (IBAction)selectCompLevel:(id)sender {
    [self.pickerView setTag:1];
    [self.Competitions setEnabled:NO];
    [self.pickerView selectRow:self.compLevel.tag inComponent:0 animated:NO];
    [self.Competitions setTag:0];
    NSString* compname=@"All competitions";
    //[[NSString alloc] initWithString:[[self.games objectAtIndex:0]compname]];
   
    [self.Competitions setTitle:compname forState:UIControlStateNormal];
    [self.Competitions setTitle:compname forState:UIControlStateDisabled];
    
    [self.compLevel setEnabled:NO];
    [self.segmentedControl setEnabled:NO];
    [self.pickerView setAlpha:0];
    [self.pickerView setHidden:NO];
    [self.pickerView reloadComponent:0];

    
    [UIView animateWithDuration:0.5 animations:^{
        self.pickerView.alpha=1;
    }];  
}


#pragma mark - TableView  delegate

// Customize the number of sections in the table view.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 67;    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.Competitions.tag==0) {
     return [self.games count];   
    }
    else {
        return 1;
    }
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.Competitions.tag==0) {
        return [[[self.games objectAtIndex:section] matches] count];
    }
    else {
        return [[[self.games objectAtIndex:self.Competitions.tag] matches] count];
    }
    return 1;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView* view;
    UILabel* label;
    view=[[UIView alloc] init];
    label=[[UILabel alloc] init];

    if (self.Competitions.tag==0) {
        
        label.text=[[self.games objectAtIndex:section] compname];
    }
    else {
        label.text=[[self.games objectAtIndex:self.Competitions.tag] compname];
    }
    
  
//    [label setBackgroundColor:[UIColor colorWithRed:.68 green:.97 blue:.18 alpha:0.8]];
    [label setBackgroundColor:[UIColor colorWithRed:.7 green:.8 blue:.2 alpha:1]];

    [label setTextColor:[UIColor colorWithRed:.1 green:.3 blue:.1 alpha:1]];
//    [label setFont:[UIFont fontWithName:@"system bold" size:9]];
    [label setFont:[UIFont systemFontOfSize:13]];
//    [label setMinimumFontSize:8];
    
   
    
    return label;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;    
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *MyIdentifier = @"MyIdentifier";
    
    GameCell *cell = (GameCell*)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"GameCellView" owner:self options:nil];
        cell=self.myCell1;
    }

    Game* thisGame;
    
    if (self.Competitions.tag==0) {
         thisGame=[[[self.games objectAtIndex:indexPath.section] matches]objectAtIndex:indexPath.row];
    }
    else {
        thisGame=[[[self.games objectAtIndex:self.Competitions.tag] matches]objectAtIndex:indexPath.row];
    }

    
    cell.roundLabel.text=[NSString stringWithFormat:@"Round: %@",thisGame.round];
    
    if ([self.title isEqualToString:kFootFixtures] || [self.title isEqualToString:kHurlFixtures]){
    cell.teamsLabel.text=[NSString stringWithFormat:@"%@ -v- %@",thisGame.club1,thisGame.club2];
    }
    else {
        cell.teamsLabel.text=[NSString stringWithFormat:@"%@ %@ v %@ %@",thisGame.club1,thisGame.club1score,thisGame.club2score, thisGame.club2];
    }
        
    
    cell.dateLabel.text=thisGame.dateString;
//    cell.refereeLabel.text=[NSString stringWithFormat:@"Referee: %@",thisGame.referee];
    cell.venueLabel.text=thisGame.venue;

    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:[UIColor colorWithRed:.05 green:.2 blue:.05 alpha:0.8]];
    cell.selectedBackgroundView=bgColorView;

 //    [cell setAccessoryView:[self makeDetailDisclosureButton]];

    [cell.textLabel setHighlightedTextColor:[UIColor whiteColor]];
    [cell.detailTextLabel setHighlightedTextColor:[UIColor whiteColor]];
    [cell setBackgroundColor:[UIColor whiteColor]];
    [cell.textLabel setFont:[UIFont fontWithName:@"system" size:12]];
    
    //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
  
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"GameCellView" owner:self options:nil];
        cell=self.myCell1;
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor clearColor]];
  
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog (@"selected row %d", indexPath.row);
    
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected accessory from row %d", indexPath.row);
}

//helper for accessoryButtonTapped
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;
    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}


- (UIButton *) makeDetailDisclosureButton {
    UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"rightarrow"] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setFrame:CGRectMake(0, 0, 40, 40)];
    
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateHighlighted];
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateSelected];
    
    
    [button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];
    
    return ( button );
}


#pragma mark - UIpickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* view1=[[UILabel alloc] init];
    [view1 setNumberOfLines:2];
    [view1 setBackgroundColor:[UIColor clearColor]];
    [view1 setFont:[UIFont fontWithName:@"bold system" size:11]];
    CGRect frame=CGRectMake(30, 0, 250, 70);
    [view1 setFrame:frame];
    
    if (row%2==0) {
        view1.textColor=[UIColor darkGrayColor];
    }
    else {
        view1.textColor=[UIColor blackColor];
    }
        
    switch (pickerView.tag) {
        case 1: {
            if (row>([kCompLevels count]-1)) row=0;
            view1.text=[kCompLevels objectAtIndex:row];
            break;
        }
        case 2: {
            if (row>([self.games count]-1)) row=0;
            NSString* compname=[[self.games objectAtIndex:row] compname];
            //            NSLog (@"compname=%@",compname);
            view1.text=compname;
            break;    
        }
        default:
            break;
    }

    return view1;
}

//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//    
//    
//    return nil;
//   
//}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    [self.segmentedControl setEnabled:YES];

    self.pickerView.alpha=1;
    [UIView animateWithDuration:0.5 animations:^{
        self.pickerView.alpha=0;
    }];   
    [self.compLevel setEnabled:YES];
    [self.Competitions setEnabled:YES];
    [self.Competitions setEnabled:YES];
    
    
    //comp level
    switch (pickerView.tag) {
        case 1: {
            [self.compLevel setTitle:[kCompLevels objectAtIndex:row] forState:UIControlStateNormal];
            [self.compLevel setTitle:[kCompLevels objectAtIndex:row] forState:UIControlStateDisabled];
            [self.compLevel setTag:row];
            [self.tableView setHidden:YES];
            self.boardItem=[NSString stringWithFormat:@"%@%@%@%@",kGameItem,self.title,[kCompPanel objectAtIndex:self.segmentedControl.selectedSegmentIndex ],self.compLevel.titleLabel.text];
            [self.activityIndicator startAnimating];
            [self.activityIndicator setHidden:NO];
            [self.errorMessage setHidden:NO];

            
                [myAppDelegate getData:[NSString stringWithFormat:@"%@compLevel=%@",self.reqURL,self.compLevel.titleLabel.text]
                               andType:self.boardItem];   

            break;
        }
        
        //competition
        case 2: {
            [self.Competitions setTitleEdgeInsets:UIEdgeInsetsMake (0, 0, 0, 30)];
            NSString* compname=[[NSString alloc] initWithString:[[self.games objectAtIndex:row]compname]];
            [self.Competitions setTitle:compname forState:UIControlStateNormal];
            [self.Competitions setTitle:compname forState:UIControlStateDisabled];
            [self.Competitions setTag:row];
            break;
        }
        default:
            break;
    }
    
    [self.tableView reloadData];
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    switch (pickerView.tag) {
        case 1: {
            return [kCompLevels count];
            break;
        }
        case 2: {
            return [self.games count];
            break;    
        }
        default:
            break;
    }    
    //default
    return 0;
    
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
 
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



@end
